{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "J:\\MyInstall\\anaconda3.6\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "\n",
    "from __future__ import division\n",
    "\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Datasets(train=<tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet object at 0x0000022730E70EF0>, validation=<tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet object at 0x0000022730E80160>, test=<tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet object at 0x0000022730E80128>)\n"
     ]
    }
   ],
   "source": [
    "print(mnist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "添加三个隐层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "#W = tf.Variable(tf.zeros([784, 10]))\n",
    "#修改为截断误差\n",
    "W1 = tf.Variable(tf.truncated_normal([784,128],stddev=0.071))\n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([128,64],stddev=0.071))\n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([64,32],stddev=0.071))\n",
    "\n",
    "W4 = tf.Variable(tf.truncated_normal([32,10],stddev=0.071))\n",
    "\n",
    "b1 = tf.Variable(tf.truncated_normal([128],stddev=0.1))\n",
    "\n",
    "b2 = tf.Variable(tf.truncated_normal([64],stddev=0.1))\n",
    "\n",
    "b3 = tf.Variable(tf.truncated_normal([32],stddev=0.1))\n",
    "\n",
    "\n",
    "b4 = tf.Variable(tf.truncated_normal([10],stddev=0.1))\n",
    "\n",
    "layer1 = tf.nn.relu(tf.matmul(x, W1) + b1)\n",
    "\n",
    "layer2 =  tf.nn.relu(tf.matmul(layer1, W2) + b2)\n",
    "                                      \n",
    "layer3 =  tf.nn.relu(tf.matmul(layer2, W3) + b3)\n",
    "\n",
    "y=tf.matmul(layer3, W4) + b4\n",
    "\n",
    "#y = tf.nn.softmax(tf.matmul(x, W) + b)\n",
    "\n",
    "#logits1 =tf.matmul(x, W1) + b1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#W2 = tf.Variable(tf.truncated_normal([100,10],stddev=0.071))\n",
    "#b2 = tf.Variable(tf.truncated_normal([10],stddev=0.1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#y=tf.matmul(logits1, W2) + b2\n",
    "#y=tf.matmul(x, W1) + b1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "\n",
    "#ll=tf.contrib.layers.l2_regularizer(0.00001)(W)\n",
    "#re=tf.contrib.layers.apply_regularization(ll)\n",
    "#cross_entropy = (tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "#ll=tf.contrib.layers.l2_regularizer(0.00001)(W)\n",
    "#cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y)))+ll\n",
    "#cross_entropy = -tf.reduce_mean(y_*tf.log(y)) +ll\n",
    "#cross_entropy = tf.losses.mean_squared_error(y, y_)+ll\n",
    "#cross_entropy=tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "#cross_entropy = (tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-10-24ad27bb5710>:10: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#l2_loss = tf.nn.l2_loss(W1) + tf.nn.l2_loss(W2)\n",
    "#total_loss = cross_entropy + 7e-5*l2_loss\n",
    "\n",
    "#l1_loss = tf.contrib.layers.l2_regularizer(0.00001)(W1)\n",
    "#l2_loss = tf.contrib.layers.l2_regularizer(0.000001)(W2)\n",
    "#l3_loss = tf.contrib.layers.l2_regularizer(0.000001)(W3)\n",
    "#total_loss = l1_loss+ l2_loss + l3_loss + cross_entropy\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "regularization_loss = tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n",
    "loss = cross_entropy + regularization_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "global_step = tf.Variable(0, trainable=False)\n",
    "starter_learning_rate = 1.0\n",
    "learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step, 1000, 0.9, staircase=True)\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss,global_step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "#train_step = tf.train.GradientDescentOptimizer(0.5).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "\n",
    "init_op = tf.global_variables_initializer()\n",
    "\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0:  0.093900\n",
      "1000:  0.941900\n",
      "2000:  0.952200\n",
      "3000:  0.962400\n",
      "4000:  0.965500\n",
      "5000:  0.966300\n",
      "6000:  0.969200\n",
      "7000:  0.969000\n",
      "8000:  0.972000\n",
      "9000:  0.969900\n",
      "10000:  0.972800\n",
      "11000:  0.972200\n",
      "12000:  0.972000\n",
      "13000:  0.972300\n",
      "14000:  0.971300\n",
      "15000:  0.973000\n",
      "16000:  0.972200\n",
      "17000:  0.972100\n",
      "18000:  0.972000\n",
      "19000:  0.972200\n",
      "20000:  0.972000\n",
      "21000:  0.972100\n",
      "22000:  0.972400\n",
      "23000:  0.972100\n",
      "24000:  0.972100\n",
      "25000:  0.972100\n",
      "26000:  0.972300\n",
      "27000:  0.972400\n",
      "28000:  0.972200\n",
      "29000:  0.972400\n",
      "30000:  0.972300\n",
      "31000:  0.972300\n",
      "32000:  0.972600\n",
      "33000:  0.972200\n",
      "34000:  0.972400\n",
      "35000:  0.972300\n",
      "36000:  0.972400\n",
      "37000:  0.972200\n",
      "38000:  0.972400\n",
      "39000:  0.972300\n",
      "40000:  0.972300\n",
      "41000:  0.972200\n",
      "42000:  0.972200\n",
      "43000:  0.972200\n",
      "44000:  0.972200\n",
      "45000:  0.972200\n",
      "46000:  0.972200\n",
      "47000:  0.972200\n",
      "48000:  0.972200\n",
      "49000:  0.972200\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for i in range(50000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "  if i % 1000 == 0:\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "    print(\"%d:  %f\"%(i,sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels})))\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "49999:  0.972200\n"
     ]
    }
   ],
   "source": [
    "  # Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "print(\"%d:  %f\"%(i,sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels})))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到92%左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至98%以上的准确率。\n",
    "Hint：\n",
    "- 多隐层\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 隐层神经元数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个step就对loss、accuracy等等进行一次输出，这样才能有根据地进行调整"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
